import 'package:github_client_app/models/user.dart';
import 'package:github_client_app/db/db_storage.dart';
import 'package:sqflite/sqflite.dart';

class UserService extends DBStorage {
  // 单例模式
  static UserService? _instance;
  factory UserService() => _instance ??= UserService._();
  UserService._();

  @override
  String tableName = "user_info";

  ///创建表
  @override
  Future<void> onCreate(Database db, int version) async {
    print("创建表");
    await db.execute("""
      CREATE TABLE $tableName (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT,
        keywords TEXT,
        age INTEGER
      )
    """);
  }

  ///查询所有
  @override
  Future<List<User>> findAll() async {
    List value = await super.findAll();
    return fromJson(value);
  }

  ///条件查询
  @override
  Future<List<User>> findBy(Map<String, Object?> where) async {
    List value = await super.findBy(where);
    return fromJson(value);
  }

  ///分页条件查询
  @override
  Future<List<User>> findPage({
    Map<String, Object?>? where,
    int page = 1,
    int pageSize = 20,
  }) async {
    List value =
        await super.findPage(where: where, page: page, pageSize: pageSize);
    return fromJson(value);
  }

  ///将json转为model
  List<User> fromJson(List value) {
    List<User> users = [];
    value.forEach((element) {
      users.add(User.fromJson(element));
    });
    return users;
  }
}
